package com.momo.hr.service;

import com.momo.hr.bean.Hr;
import com.momo.hr.bean.Menu;
import com.momo.hr.mapper.MenuMapper;
import com.momo.hr.mapper.MenuRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    MenuRoleMapper menuRoleMapper;

    /**拿到对应角色的菜单列表
     * 从SpringSecurity中获取当前的的用户Id
     * @return List
     */
    public List<Menu> getMenusByHrId(){
        //拿到当前用户
        Hr currentUser = (Hr)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return this.menuMapper.getMenusByHrId(currentUser.getId());
    }

    /**
     * 拿到对应的角色的菜单,需要用到了Spring的缓存技术
     * @return List<Menu>
     */

    //@Cacheable
    public List<Menu> getAllMenuWithRole(){
        return menuMapper.getAllMenusWithRole();
    }

    //拿到所有的菜单
    public List<Menu> getAllMenusWithChildren() {
        return this.menuMapper.getAllMenus();
    }
    //查询对应角色的菜单权限
    public List<Integer> getMidByRid(Integer rid) {
        return this.menuMapper.getMidsByRid(rid);
    }

    /**权限的业务辑
     *  通过rid 删除所有的权信息，然后再把已经选择的id赋值进去
     * @param rid
     * @param mids
     * @return Boolean
     */
    public boolean updateMenuRole(Integer rid, Integer[] mids) {
        if(mids == null){
            this.menuRoleMapper.deleteByRid(rid);
            return true;
        }
        this.menuRoleMapper.deleteByRid(rid);
        Integer integer = this.menuRoleMapper.insertRecord(rid, mids);
        if(integer == mids.length){
            return true;
        } else {
            return false;
        }
    }
}
